package com.springboot_shiyan3.service;

import com.springboot_shiyan3.Bean.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class Restemplate {

    private static String CORONA_VIRUS_DATA_URL =
            "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    private final  List<RegionStats> list = new ArrayList<>();


    @Scheduled(cron = "${lhc.exp3.schedule.updateCron}")
    public void fetchCron() throws IOException {
        RequestEntity<Void> requestEntiy = RequestEntity
                .<Void>get(URI.create(CORONA_VIRUS_DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent",""))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntiy, Resource.class);
        Resource body = exchange.getBody();

        if (!list.isEmpty()) list.clear();

        Reader reader = new InputStreamReader(Objects.requireNonNull(body).getInputStream());
        CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
        for(CSVRecord record : parser){
            String state = record.get("Province/State");
            String country = record.get("Country/Region");

            int latest = Integer.parseInt(record.get(record.size() - 1));
            int diffFrom = Integer.parseInt(record.get(record.size() - 1))
                    - Integer.parseInt(record.get(record.size() - 2));

            RegionStats re = new RegionStats(state,country,latest,diffFrom);
            list.add(re);

        }
    }

    public List<RegionStats> getSpecificRegionStatsSet(String country){
        return getALLRegionStatsSet().parallelStream()
                .filter(rs -> rs.getCountry().equals(country))
                .collect(Collectors.toUnmodifiableList());
    }

    public List<RegionStats> getALLRegionStatsSet() {
        return list;
    }

    @Bean
    CommandLineRunner invokeWhenRun(){
        return out -> fetchCron();
    }

}
